#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>

const int num = 5;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *runThread(void* args)
{
    std::string name = static_cast<char*>(args);

    while(1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex); // pthread_cond_wait，调用的时候，会自动释放锁

        //线程会阻塞在这里
        std::cout << name << " 活动" << std::endl;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t tid[num];

    for(int i = 0; i < num; ++i)
    {
        char* name = new char[32];
        snprintf(name, 64, "thread-%d", i+1);
        pthread_create(tid+i, nullptr, runThread, name);
    }

    sleep(3);//3秒之后，每一秒释放一个线程.

    while(true)
    {
        std::cout << "main thread wakeup thread..." << std::endl;
        //pthread_cond_signal(&cond);//一次处理一个线程
        pthread_cond_broadcast(&cond);
        sleep(1);
    }

    for(int i = 0; i < num; ++i)
    {
        pthread_join(tid[i], nullptr);
    }
    return 0;
}